package badugaserver;
import java.util.ArrayList;
import java.util.Random;

/**
 * @author Wojtek N., Kamil M.
 * @version 0.7
 * Class which defines deck of fifty two cards.
 */
public class Deck 
{
	private static ArrayList<Card> cards;
	private static ArrayList<Card> graveyard;
	
	/**
	 * Constructor of the class Deck.
	 */
	public Deck()
	{
		cards = new ArrayList<Card>();
		graveyard = new ArrayList<Card>();
		try
		{
			for(int i=1; i<5; i++)
			{
				for(int j=1; j<14; j++)
				{
					cards.add(new Card(j,i));
				}
			}
		}
		catch (BadugaExceptions be)
		{
			be.getMessage();
		}
		shuffleDeck();
	}
	
	/**
	 * Method which shuffles deck.
	 */
	public void shuffleDeck ()
	{
		Random rnd = new Random();
		for(int i = 0; i < cards.size(); i++)
		{
			int rndPlace = rnd.nextInt(cards.size() - 1);
			Card temp1 = cards.get(i);
			Card temp2 = cards.get(rndPlace);
			cards.set(i, temp2);
			cards.set(rndPlace, temp1);
		}
	}
	
	/**
	 * Method for exchanging card for player.
	 */
	public Card swapCard(Card c)
	{
		graveyard.add(c);
		return drawFromDeck();
	}
	
	/**
	 * Method for drawing one card ("top deck").
	 */
	public Card drawFromDeck()
	{
		if(cards.isEmpty())
		{
			graveToDeck();
		}
		return cards.remove(0);
	}
	
	/**
	 * @return deck size.
	 */
	public int deckSize()
	{
		return cards.size();
	}
	
	/**
	 * When deck is empty this method transfer cards from graveyard to deck.
	 */
	private void graveToDeck()
	{
		for(int i = 0; i < graveyard.size(); i++)
		{
			cards.add(graveyard.remove(0));
		}
		graveyard.clear();
		shuffleDeck();
	}
}
